package at.irian.jsfatwork.service.impl;

import at.irian.jsfatwork.dao.AddressDao;
import at.irian.jsfatwork.dao.CustomerDao;
import at.irian.jsfatwork.dao.OrderDao;
import at.irian.jsfatwork.domain.Address;
import at.irian.jsfatwork.domain.Customer;
import at.irian.jsfatwork.domain.Order;
import at.irian.jsfatwork.service.CustomerService;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.Date;
import java.util.List;

@Named("customerService")
@Singleton
public class CustomerServiceImpl implements CustomerService {
    @Inject
    private CustomerDao customerDao;
    @Inject
    private AddressDao addressDao;
    @Inject
    private OrderDao orderDao;

    public Customer createNew() {
        return customerDao.createNew();
    }

    @Transactional
    public void save(Customer customer) {
        customerDao.persist(customer);
    }

    @Transactional
    public void delete(Customer customer) {
        customerDao.delete(customer);
    }

    @Transactional(readOnly = true)
    public List<Customer> findAll() {
        return customerDao.findAll();
    }

    @Transactional(readOnly = true)
    public Customer findById(long id) {
        return customerDao.findById(id);
    }

    public Address createAddress(Customer customer) {
        Address address = addressDao.createNew();
        address.setCustomer(customer);
        return address;
    }

    @Transactional
    public void saveAddress(Address address) {
        if (address.isTransient()) {
            addressDao.persist(address);
            address.getCustomer().addAddress(address);
        }
    }

    @Transactional
    public void deleteAddress(Address address) {
        address.getCustomer().getAddresses().remove(address);
        addressDao.delete(address);
    }

    public Order createOrder(Customer customer) {
        Order order = orderDao.createNew();
        order.setCustomer(customer);
        return order;
    }

    @Transactional
    public void saveOrder(Order order) {
        order.setOrderDate(new Date());
        order.getCustomer().getOrders().add(order);
        orderDao.persist(order);
    }

}
